package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.codec.Base64;
import com.atguigu.tingshu.album.config.VodConstantProperties;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.util.UploadFileUtil;
import com.atguigu.tingshu.vo.album.TrackMediaInfoVo;
import com.qcloud.vod.VodUploadClient;
import com.qcloud.vod.model.VodUploadRequest;
import com.qcloud.vod.model.VodUploadResponse;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ims.v20201229.ImsClient;
import com.tencentcloudapi.ims.v20201229.models.ImageModerationRequest;
import com.tencentcloudapi.ims.v20201229.models.ImageModerationResponse;
import com.tencentcloudapi.tms.v20201229.TmsClient;
import com.tencentcloudapi.tms.v20201229.models.TextModerationRequest;
import com.tencentcloudapi.tms.v20201229.models.TextModerationResponse;
import com.tencentcloudapi.vod.v20180717.VodClient;
import com.tencentcloudapi.vod.v20180717.models.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class VodServiceImpl implements VodService {

    @Autowired
    private VodConstantProperties vodConstantProperties;
    @Autowired
    private VodUploadClient vodUploadClient;

    @Override
    public Map<String, String> uploadTrack(MultipartFile file) {
        try {
            //1.将服务器端接收文件保存本地磁盘
            String filePath = UploadFileUtil.uploadTempPath(vodConstantProperties.getTempPath(), file);
            //2.将文件上传到腾讯云点播平台
            //2.1 构造上传请求对象-封装本地文件路径
            VodUploadRequest request = new VodUploadRequest();
            request.setMediaFilePath(filePath);
            //2.2 调用上传方法，传入接入点地域及上传请求。
            VodUploadResponse response = vodUploadClient.upload(vodConstantProperties.getRegion(), request);
            //2.3 上传成功后，获取上传后文件信息
            if (response != null) {
                String fileId = response.getFileId();
                String mediaUrl = response.getMediaUrl();
                Map<String, String> map = new HashMap<>();
                map.put("mediaFileId", fileId);
                map.put("mediaUrl", mediaUrl);
                return map;
            }
            return null;
        } catch (Exception e) {
            log.error("[专辑服务]文件上传云点播平台异常：{}", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取点播平台音频详情信息
     *
     * @param mediaFileId 文件唯一标识
     * @return
     */
    @Override
    public TrackMediaInfoVo getTrackMediaInfo(String mediaFileId) {
        try {
            //1.实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            Credential cred = new Credential(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());
            //2.实例化要请求产品的client对象,clientProfile是可选的
            VodClient client = new VodClient(cred, "ap-chengdu");
            //3.实例化一个请求对象,每个接口都会对应一个request对象
            DescribeMediaInfosRequest req = new DescribeMediaInfosRequest();
            String[] fileIds1 = {mediaFileId};
            req.setFileIds(fileIds1);
            //4.执行接口调用，返回的resp是一个DescribeMediaInfosResponse的实例，与请求对象对应
            DescribeMediaInfosResponse resp = client.DescribeMediaInfos(req);
            //5.解析响应结果
            if (resp != null) {
                MediaInfo[] mediaInfoSet = resp.getMediaInfoSet();
                MediaInfo mediaInfo = mediaInfoSet[0];
                if (mediaInfo != null) {
                    //5.1 解析获取基础信息（basicInfo）：包括媒体名称、分类、播放地址、封面图片等。
                    MediaBasicInfo basicInfo = mediaInfo.getBasicInfo();
                    //5.2 解析元信息（metaData）：包括大小、时长、视频流信息、音频流信息等。
                    MediaMetaData metaData = mediaInfo.getMetaData();
                    //5.3 封装音频文件VO结果对象
                    TrackMediaInfoVo vo = new TrackMediaInfoVo();
                    vo.setType(basicInfo.getType());
                    vo.setDuration(metaData.getDuration());
                    vo.setSize(metaData.getSize());
                    return vo;
                }
            }
        } catch (Exception e) {
            log.error("[专辑服务]调用腾讯点播平台异常：{}", e);
            throw new RuntimeException(e);
        }
        return null;
    }

    /**
     * 对指定点播平台文件进行开启异步审核任务
     *
     * @param mediaFileId 审核任务id
     * @return
     */
    @Override
    public String startReviewTask(String mediaFileId) {
        try {
            //1.实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            Credential cred = new Credential(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());
            //2.实例化要请求产品的client对象,clientProfile是可选的
            VodClient client = new VodClient(cred, vodConstantProperties.getRegion());
            //3.实例化一个请求对象,每个接口都会对应一个request对象
            ReviewAudioVideoRequest req = new ReviewAudioVideoRequest();
            req.setFileId(mediaFileId);
            //4.返回的resp是一个ReviewAudioVideoResponse的实例，与请求对象对应
            ReviewAudioVideoResponse resp = client.ReviewAudioVideo(req);
            if (resp != null) {
                return resp.getTaskId();
            }
        } catch (Exception e) {
            log.error("[专辑服务]发生音视频文件审核失败：{}", e);
        }
        return null;
    }

    @Override
    public void deleteMedia(String mediaFileId) {
        try {
            //1.实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            Credential cred = new Credential(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());
            //2.实例化要请求产品的client对象
            VodClient client = new VodClient(cred, vodConstantProperties.getRegion());
            //3.实例化一个请求对象,每个接口都会对应一个request对象
            DeleteMediaRequest req = new DeleteMediaRequest();
            req.setFileId(mediaFileId);
            //4.返回的resp是一个DeleteMediaResponse的实例，与请求对象对应
            client.DeleteMedia(req);
        } catch (TencentCloudSDKException e) {
            log.error("点播平台，删除文件失败：{}", e);
        }
    }

    /**
     * 文本内容审核
     *
     * @param content
     * @return
     */
    @Override
    public Boolean scanText(String content) {
        Boolean flag = false;
        try {
            //1.实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            Credential cred = new Credential(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());
            //2.实例化要请求产品的client对象,clientProfile是可选的
            TmsClient client = new TmsClient(cred, "ap-beijing");
            //3.实例化一个请求对象,每个接口都会对应一个request对象
            TextModerationRequest req = new TextModerationRequest();
            //4.对审核内容进行Base64编码
            String encodeContent = Base64.encode(content);
            req.setContent(encodeContent);
            //5.解析获取内容审核建议
            TextModerationResponse resp = client.TextModeration(req);
            if (resp != null) {
                String suggest = resp.getSuggestion().toLowerCase();
                if ("pass".equals(suggest)) {
                    flag = true;
                }
            }
            return flag;
        } catch (Exception e) {
            log.error("[专辑服务]文本审核异常：{}", e);
            return false;
        }
    }

    /**
     * @param file
     * @return
     */
    @Override
    public Boolean scanImage(MultipartFile file) {
        Boolean flag = false;
        try {
            //1.实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            Credential cred = new Credential(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());
            //2.实例化要请求产品的client对象,clientProfile是可选的
            ImsClient client = new ImsClient(cred, vodConstantProperties.getRegion());
            //3.实例化一个请求对象,每个接口都会对应一个request对象
            ImageModerationRequest req = new ImageModerationRequest();
            //对图片进行Base64编码
            String encodeImage = Base64.encode(file.getInputStream());
            req.setFileContent(encodeImage);
            //4.返回的resp是一个ImageModerationResponse的实例，与请求对象对应
            ImageModerationResponse resp = client.ImageModeration(req);
            if (resp != null) {
                String suggest = resp.getSuggestion().toLowerCase();
                if ("pass".equals(suggest)) {
                    flag = true;
                }
            }
            return flag;
        } catch (Exception e) {
            log.error("[专辑服务]图片审核异常：{}", e);
            return flag;
        }
    }

    /**
     * 根据审核任务ID查询审核结果
     *
     * @param reviewTaskId
     * @return 建议
     */
    @Override
    public String getReviewTaskSuggest(String reviewTaskId) {
        try {
            //1.实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            Credential cred = new Credential(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());
            //2.实例化要请求产品的client对象,clientProfile是可选的
            VodClient client = new VodClient(cred, "");
            //3.实例化一个请求对象,每个接口都会对应一个request对象
            DescribeTaskDetailRequest req = new DescribeTaskDetailRequest();
            req.setTaskId(reviewTaskId);
            //4.返回的resp是一个DescribeTaskDetailResponse的实例，与请求对象对应
            DescribeTaskDetailResponse resp = client.DescribeTaskDetail(req);
            if (resp != null) {
                //5.解析审核任务状态以及审核建议
                String taskType = resp.getTaskType();
                if ("ReviewAudioVideo".equals(taskType)) {
                    String status = resp.getStatus();
                    if ("FINISH".equals(status)) {
                        ReviewAudioVideoTask reviewAudioVideoTask = resp.getReviewAudioVideoTask();
                        ReviewAudioVideoTaskOutput output = reviewAudioVideoTask.getOutput();
                        String suggestion = output.getSuggestion().toLowerCase();
                        return suggestion;
                    }
                }
            }
        } catch (Exception e) {
            log.error("[专辑服务]获取音视频审核异常：{}", e);
        }
        return null;
    }
}
